import * as _ from "lodash"
import { PageList } from "../data"
import httpClient from "../httpclient"
import { Blob, BlobType } from "../storage"


class StoreBlobQuery {
  private storeId_: string
  private params = {}

  public page(page: number) {
    this.params["page"] = page
    return this
  }

  public limit(limit: number) {
    this.params["limit"] = limit
    return this
  }

  public storeId(storeId: string) {
    this.storeId_ = storeId
    return this
  }

  public path(path: string) {
    this.params["path"] = path
    return this
  }

  public directory() {
    this.params["type"] = BlobType.Directory
    return this
  }

  public file() {
    this.params["type"] = BlobType.File
    return this
  }

  public list(): Promise<PageList<Blob>> {
    return httpClient.get(`/v1/stores/${this.storeId_}/blobs`, { params: this.params })
      .then(({ data }) => {
        return _.assign(PageList.empty(), data, {
          elements: _.map(data.elements, element => _.assign(new Blob(), element)),
        })
      })
  }
}

export interface BlobResource {
  storeId: string
  path: string
  name?: string
  file?: any
}

export class StoreBlobServiceV1 {

  public static storeBlob(resource: BlobResource): Promise<Blob> {
    const formData = new FormData()
    formData.append("file", resource.file)
    if (!_.isUndefined(resource.name)) {
      formData.append("name", resource.name)
    }

    const path = _.startsWith(resource.path, "/") ? resource.path : "/" + resource.path
    return httpClient.post(`/v1/stores/${resource.storeId}/blobs${path}`, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }).then(({ data }) => _.assign(new Blob(), data))
  }

  public static deleteBlob(storeId: string, path: string): Promise<void> {
    return httpClient.delete(`/v1/stores/${storeId}/blobs${path}`)
  }

  public static deleteBlobs(storeId: string, paths: string[]): Promise<void> {
    return httpClient.delete(`/v1/stores/${storeId}/blobs/batch`, {
      data: paths,
    })
  }

  public static getBlobs(): StoreBlobQuery {
    return new StoreBlobQuery()
  }
}
